package com.myCommunity.ui;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.myCommunity.dao.impl.UsersDaoImpl;
import com.myCommunity.entity.Users;

public class PersonalDataServlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//创建工厂
		FileItemFactory factory = new DiskFileItemFactory();
		//创建upload对象
		ServletFileUpload upload = new ServletFileUpload(factory);
		String nickname = null;
		String signature = null;
		String password = null;
		String filename = null;
		String path = null;
		
		//获取需要修改的对象
		Users user = (Users) request.getSession().getAttribute("user");
		try {
			List<FileItem> items = upload.parseRequest(request);
			for(FileItem item : items){
				//判断item是否为表单内容
				if(item.isFormField()){
					if("confirm".equals(item.getFieldName()))
						password = item.getString("UTF-8");
					if("nickname".equals(item.getFieldName()))
						nickname = item.getString("UTF-8");
					if("signature".equals(item.getFieldName()))
						signature = item.getString("UTF-8");
				}else{
					//获取上传文件原来的文件名
					String client = item.getName();
					//更改文件名
					
					if(!client.substring(client.lastIndexOf(".")).equals(".jpg")){
						request.setAttribute("error", "照片格式须为jpg");
						request.getRequestDispatcher("personalData.jsp").forward(request, response);
					} 
					filename = user.getId()+client.substring(client.lastIndexOf("."));
					ServletContext application = request.getSession().getServletContext();
					path = "C:\\程序设计\\作业\\Hibernate\\WebRoot\\Content\\pictures\\user\\"+filename;
					item.write(new File(path));
				}
			}
			user.setNickname(nickname);
			user.setSignature(signature);
			user.setPassword(password);
			user.setFilename(filename);
			
			new UsersDaoImpl().update(user);
			
			response.sendRedirect("PersonalDataServlet");
				
		} catch (Exception e) {
			// TODO: handle exception
		}
		
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Users user = (Users) request.getSession().getAttribute("user");
		request.setAttribute("user", user);
		//获取filename
		request.setAttribute("filename", user.getFilename());
		
		request.getRequestDispatcher("/afterLogin/personalData.jsp").forward(request, response);
	}

}
